import { ref, computed } from 'vue'

export function useMaterialCalculation() {
  const materials = ref([])
  const thick = ref({
    a: "",
    b: "",
    c: "",
    d: "",
    e: ""
  })

  // 材料单价和重量
  const caidanprice1 = ref(0)
  const caike1 = ref(0)
  const caidanprice2 = ref(0)
  const caike2 = ref(0)
  const caidanprice3 = ref(0)
  const caike3 = ref(0)
  const caidanprice4 = ref(0)
  const caike4 = ref(0)
  const caidanprice5 = ref(0)
  const caike5 = ref(0)

  // 计算单个材料的重量和价格
  const calculateMaterial = (index, thickness) => {
    const material = materials.value.find(item => item.materialName === form.value[`ca${index}`])
    if (!material) return { weight: 0, price: 0 }

    const thicknessInCm = (thickness || material.thickness) * 0.0001
    const gramPerSquareMeter = material.density * thicknessInCm * 10000
    const pricePerSquareMeter = truncateDecimals(gramPerSquareMeter * material.pricePerGram, 6)

    return {
      weight: gramPerSquareMeter,
      price: pricePerSquareMeter,
      thickness: thickness || material.thickness
    }
  }

  // 更新材料计算
  const updateMaterial = (index, val, thickness) => {
    const result = calculateMaterial(index, thickness)
    
    switch(index) {
      case 1:
        caike1.value = result.weight
        caidanprice1.value = result.price
        thick.value.a = result.thickness
        break
      case 2:
        caike2.value = result.weight
        caidanprice2.value = result.price
        thick.value.b = result.thickness
        break
      case 3:
        caike3.value = result.weight
        caidanprice3.value = result.price
        thick.value.c = result.thickness
        break
      case 4:
        caike4.value = result.weight
        caidanprice4.value = result.price
        thick.value.d = result.thickness
        break
      case 5:
        caike5.value = result.weight
        caidanprice5.value = result.price
        thick.value.e = result.thickness
        break
    }
  }

  // 材料总重量和总价
  const materialTotalWeight = computed(() => {
    return (
      Number(caike1.value) +
      Number(caike2.value) +
      Number(caike3.value) +
      Number(caike4.value) +
      Number(caike5.value) +
      3 * Number(chen.value)
  })

  const materialTotalPrice = computed(() => {
    return Number(
      (caidanprice1.value +
        caidanprice2.value +
        caidanprice3.value +
        caidanprice4.value +
        caidanprice5.value).toFixed(6))
  })

  return {
    materials,
    thick,
    caidanprice1,
    caike1,
    caidanprice2,
    caike2,
    caidanprice3,
    caike3,
    caidanprice4,
    caike4,
    caidanprice5,
    caike5,
    updateMaterial,
    materialTotalWeight,
    materialTotalPrice
  }
}